package com.blog.servlet;

import cn.hutool.core.codec.Base64;
import com.blog.entity.User;
import com.blog.service.UserService;
import com.blog.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

	UserService userService = new UserServiceImpl();

	@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            response.setContentType("text/html;charset=UTF-8");
            request.setCharacterEncoding("UTF-8");

            //获取用户名和密码
            String name = request.getParameter("userName");
            //Base64加密
            String password = Base64.encode(request.getParameter("password"));
            //创建session
            HttpSession hs = request.getSession();
            //设置标识（判断数据是否为空的标识）
            boolean flag=true;
            //查询数据库的数据（是否数数据）
            User user = userService.Login(name, password);
			
            if(user!=null){
                  flag=false;
                  hs.setAttribute("user",user);
//                  重定向 判断是否有非法用户
                  response.sendRedirect("IndexServlet");
                }else{
                hs.setAttribute("errorMsg","账号或密码不正确");
                response.sendRedirect("login.jsp");
            }
            if(flag){
            	//请求转发
                request.getRequestDispatcher("login.jsp");
            }

        }catch(

	Exception e)
	{
		e.printStackTrace();
	}
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
}
